package edu.neu.cs6515.xml.converter;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import edu.neu.cs6515.xml.Bad;
import edu.neu.cs6515.xml.False;
import edu.neu.cs6515.xml.Tile;
import edu.neu.cs6515.xml.w12.RemoteTurnResults;
import edu.neu.cs6515.xml.w12.Rerack;
import edu.neu.cs6515.xml.w12.True;

public class RemoteTurnResultsConverter implements Converter {

    @Override
    public boolean canConvert(final Class type) {
        return RemoteTurnResults.class.equals(type);
    }

    @Override
    public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
        RemoteTurnResults rtr = (RemoteTurnResults) source;
        for (Object obj : rtr.getResults()) {
            if (obj instanceof True) {
                writer.startNode("true");
                writer.endNode();
            } else if (obj instanceof False) {
                writer.startNode("false");
                writer.endNode();
            } else if (obj instanceof Tile) {
                Tile tile = (Tile) obj;
                writer.startNode("tile");
                context.convertAnother(tile);
                writer.endNode();
            } else if (obj instanceof Rerack) {
                Rerack rerack = (Rerack) obj;
                writer.startNode("rerack");
                for (Tile tile : rerack.getTile()) {
                    writer.startNode("tile");
                    context.convertAnother(tile);
                    writer.endNode();
                }
                writer.endNode();
            } else if (obj instanceof Bad) {
                writer.startNode("bad");
                writer.addAttribute("reason", ((Bad) obj).getReason());
                writer.endNode();
            }
        }
    }

    @Override
    public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
        // TODO Auto-generated method stub
        return null;
    }

}
